package com.adabank.config;

import com.adabank.controller.Controller;
import com.adabank.dao.LoginMapper;
import com.adabank.module.Login;
import com.adabank.module.LoginExample;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    LoginMapper loginMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
//        为登录用户添加权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        Login currentUser = (Login) subject.getPrincipal();//拿到user对象
        //设置当前用户的角色
        info.addRole(currentUser.getRole());
        return info;
    }

    //    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");

        LoginExample loginExample = new LoginExample();
        LoginExample.Criteria criteria = loginExample.createCriteria();

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        List<Login> loginList;
        if (criteria.andUsernameEqualTo(token.getUsername()) != null) {
            loginList = loginMapper.selectByExample(loginExample);
            return new SimpleAuthenticationInfo(loginList.get(0), loginList.get(0).getPassword(), getName());
        }
        return null;
    }
}
